package datasource

import (
	"fmt"
	"net/http"
	"sync"
)

// 创建唯一的工厂实例
var GPointFactory pointFactory
const (
	PointStatus = "point_status"
	PointDelay = "point_delay"
)

type PointCollector interface {
	// 采集数据
	Collect() interface{}

	// 数据转换
	DataConvert(interface{}) []byte

	// 数据上报
	DataReport([]byte) bool

	// 工作函数
	Work()
}

type PointConfig struct {
	PointClient *http.Client
	PointStatusUrl string
	PointDelayUrl string
	PointLoginUrl string
	PointInterval int64
}

type pointFactory struct {
	mu sync.Mutex
	works map[string]PointCollector
	config PointConfig
}

func (w *pointFactory)CreateCollector(name string) (PointCollector, bool) {
	if name == "" {
		fmt.Printf("[factor] create failed : name nil\n")
		return nil, false
	}
	var ret PointCollector
	switch name {
		case PointStatus:
			// 创建状态收集器
			ok, v := CreatePointStat()
			if ok {
				ret = v
			}
		case PointDelay:
			// 创建时延收集器
			ok, v := CreatePointDelay()
			if ok {
				ret = v
			}
		default:
			ret = nil
			fmt.Printf("[factor] create failed : name %s not support\n", name)
	}
	if ret == nil {
		return ret, false
	} else {
		return ret, true
	}
}

func (w *pointFactory)RegPointServer(name string, server PointCollector) bool {
	w.mu.Lock()
	defer w.mu.Unlock()
	if name == "" || server == nil {
		return false
	}

	// 判断是否注册过
	_, ok := w.works[name]
	if ok {
		return true
	}

	// 注册
	w.works[name] = server

	return true
}

func (w *pointFactory)GetPointServer(name string) (bool, PointCollector) {
	w.mu.Lock()
	defer w.mu.Unlock()
	if name == "" {
		return false, nil
	}
	v, ok := w.works[name]
	if !ok {
		return false, nil
	}
	return true, v
}

func (w *pointFactory)SetConfig(poitConfig PointConfig) bool {
	w.mu.Lock()
	defer w.mu.Unlock()
	w.config = poitConfig
	return true
}

func init() {
	GPointFactory = pointFactory{}
	GPointFactory.works = make(map[string]PointCollector)
	fmt.Printf("[factor] create point factor success\n")
}
